package com.wangzhenyu.common.util.log

import android.os.Environment
import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.lang.Deprecated

@Suppress("UNUSED")
@Deprecated
object LogUtil {

    private const val VERBOSE = 1
    private const val DEBUG = 2
    private const val INFO = 3
    private const val WARN = 4
    private const val ERROR = 5
    private var level = VERBOSE


    fun v(tag: String, msg: String) {
        if (level <= VERBOSE) {
            Log.v(tag.sub(), msg)
        }

    }

    fun d(tag: String, msg: String) {
        if (level <= DEBUG) {
            Log.d(tag.sub(), msg)
        }

    }

    fun i(tag: String, msg: String) {
        if (level <= INFO) {
            Log.i(tag.sub(), msg)
        }

    }

    fun w(tag: String, msg: String) {
        if (level <= WARN) {
            Log.w(tag.sub(), msg)
        }

    }

    fun e(tag: String, msg: String) {
        if (level <= ERROR) {
            Log.e(tag.sub(), msg)
        }

    }

    //Log里TAG的长度不能超过23，所以这里截取20个
    private fun String.sub(): String {
        return if (length > 20) {
            substring(0,19)
        } else {
            this
        }
    }


    fun default01(msg: String, tag: String = "WZY1") {
        Log.d(tag, msg)
    }

    fun default02(msg: String, tag: String = "WZY2") {
        Log.d(tag, msg)
    }

    fun default03(msg: String, tag: String = "WZY3") {
        Log.d(tag, msg)
    }

    fun success(msg: String = "成功", tag: String = "WZYDefault") {
        Log.d(tag, msg)
    }

    fun fail(msg: String = "失败", tag: String = "WZYDefault") {
        Log.d(tag, "\n" + msg)
    }

    //assess 评估
    fun assess(function: () -> Boolean) {
        if (function.invoke())
            success()
        else
            fail()
    }

    //在手机存储中写入数据
    fun storage(content: String) {
        val path =
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "log.txt"
        File(path).apply {
            if (!exists()) {
                createNewFile()
            }
        }
        var bufferedWriter: BufferedWriter? = null

        try {
            bufferedWriter = BufferedWriter(FileWriter(path, true))
            bufferedWriter.write(content + "\n")
        } catch (e: Exception) {
            default01(e.message.toString())
        } finally {
            bufferedWriter?.close()
        }
    }

    fun storageClean() {
        val path =
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "log.txt"
        File(path).apply {
            if (exists()) {
                delete()
            }
        }
    }
}